{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Agents\n",
    "The core idea of agents is to use a language model to choose a sequence of actions to take. In chains, a sequence of actions is hardcoded (in code). In agents, a language model is used as a reasoning engine to determine which actions to take and in which order.\n",
    "\n",
    "代理的核心思想是使用语言模型来选择要执行的一系列操作。在链中，一系列操作被硬编码（在代码中）。在代理中，语言模型用作推理引擎，以确定要执行哪些操作以及按什么顺序执行。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define tools"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Langsmith"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"LANGCHAIN_PROJECT\"] = \"agents\"\n",
    "os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
    "os.environ[\"LANGCHAIN_API_KEY\"] = \"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\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tavily"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"TAVILY_API_KEY\"] = \"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\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.tools.tavily_search import TavilySearchResults\n",
    "\n",
    "search = TavilySearchResults()\n",
    "search.invoke(\"what is the weather in SF\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Retriever"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.document_loaders import WebBaseLoader\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain_text_splitters import RecursiveCharacterTextSplitter\n",
    "\n",
    "loader = WebBaseLoader(\"https://docs.smith.langchain.com/overview\")\n",
    "docs = loader.load()\n",
    "documents = RecursiveCharacterTextSplitter(\n",
    "    chunk_size=1000, chunk_overlap=200\n",
    ").split_documents(docs)\n",
    "vector = FAISS.from_documents(documents, OpenAIEmbeddings())\n",
    "retriever = vector.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='description=\"A sample dataset in LangSmith.\")client.create_examples(    inputs=[        {\"postfix\": \"to LangSmith\"},        {\"postfix\": \"to Evaluations in LangSmith\"},    ],    outputs=[        {\"output\": \"Welcome to LangSmith\"},        {\"output\": \"Welcome to Evaluations in LangSmith\"},    ],    dataset_id=dataset.id,)# Define your evaluatordef exact_match(run, example):    return {\"score\": run.outputs[\"output\"] == example.outputs[\"output\"]}experiment_results = evaluate(    lambda input: \"Welcome \" + input[\\'postfix\\'], # Your AI system goes here    data=dataset_name, # The data to predict and grade over    evaluators=[exact_match], # The evaluators to score the results    experiment_prefix=\"sample-experiment\", # The name of the experiment    metadata={      \"version\": \"1.0.0\",      \"revision_id\": \"beta\"    },)import { Client, Run, Example } from \"langsmith\";import { evaluate } from \"langsmith/evaluation\";import { EvaluationResult } from \"langsmith/evaluation\";const client = new', metadata={'source': 'https://docs.smith.langchain.com/overview', 'title': 'Get started with LangSmith | 🦜️🛠️ LangSmith', 'description': 'LangSmith is a platform for building production-grade LLM applications. It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence. Use of LangChain is not necessary - LangSmith works on its own!', 'language': 'en'})"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retriever.invoke(\"how to upload a dataset\")[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.tools.retriever import create_retriever_tool\n",
    "\n",
    "retriever_tool = create_retriever_tool(\n",
    "    retriever,\n",
    "    \"langsmith_search\",\n",
    "    \"Search for information about LangSmith. For any questions about LangSmith, you must use this tool!\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [search, retriever_tool]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create the agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "from langchain.agents import create_tool_calling_agent\n",
    "from langchain.agents import AgentExecutor\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-3.5-turbo-0125\", temperature=0)\n",
    "\n",
    "prompt  = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a helpful assistant\"),\n",
    "        (\"placeholder\", \"{chat_history}\"),\n",
    "        (\"human\", \"{input}\"),\n",
    "        (\"placeholder\", \"{agent_scratchpad}\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "agent = create_tool_calling_agent(llm, tools, prompt)\n",
    "\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run the agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mHello! How can I assist you today?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'hi!', 'output': 'Hello! How can I assist you today?'}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"hi!\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `langsmith_search` with `{'query': 'LangSmith testing'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[33;1m\u001b[1;3mGet started with LangSmith | 🦜️🛠️ LangSmith\n",
      "\n",
      "Skip to main contentGo to API DocsSearchRegionUSEUGo to AppQuick startTutorialsHow-to guidesConceptsReferencePricingSelf-hostingLangGraph CloudQuick startOn this pageGet started with LangSmithLangSmith is a platform for building production-grade LLM applications. It allows you to closely monitor and evaluate your application, so you can ship quickly and with confidence. Use of LangChain is not necessary - LangSmith works on its own!1. Install LangSmith​PythonTypeScriptpip install -U langsmithyarn add langchain langsmith2. Create an API key​To create an API key head to the Settings page. Then click Create API Key.3. Set up your environment​Shellexport LANGCHAIN_TRACING_V2=trueexport LANGCHAIN_API_KEY=<your-api-key># The below examples use the OpenAI API, though it's not necessary in generalexport OPENAI_API_KEY=<your-openai-api-key>4. Log your first trace​We provide multiple ways to log traces to LangSmith. Below, we'll highlight\n",
      "\n",
      "\"revision_id\": \"beta\"    },)import { Client, Run, Example } from \"langsmith\";import { evaluate } from \"langsmith/evaluation\";import { EvaluationResult } from \"langsmith/evaluation\";const client = new Client();// Define dataset: these are your test casesconst datasetName = \"Sample Dataset\";const dataset = await client.createDataset(datasetName, {  description: \"A sample dataset in LangSmith.\",});await client.createExamples({  inputs: [    { postfix: \"to LangSmith\" },    { postfix: \"to Evaluations in LangSmith\" },  ],  outputs: [    { output: \"Welcome to LangSmith\" },    { output: \"Welcome to Evaluations in LangSmith\" },  ],  datasetId: dataset.id,});// Define your evaluatorconst exactMatch = async (  run: Run,  example: Example): Promise<EvaluationResult> => {  return {    key: \"exact_match\",    score: run.outputs?.output === example?.outputs?.output,  };};await evaluate(  (input: { postfix: string }) => ({ output: `Welcome ${input.postfix}` }),  {    data: datasetName,    evaluators:\n",
      "\n",
      "score: run.outputs?.output === example?.outputs?.output,  };};await evaluate(  (input: { postfix: string }) => ({ output: `Welcome ${input.postfix}` }),  {    data: datasetName,    evaluators: [exactMatch],    metadata: {      version: \"1.0.0\",      revision_id: \"beta\",    },  });Learn more about evaluation in the how-to guides.Was this page helpful?You can leave detailed feedback on GitHub.NextTutorials1. Install LangSmith2. Create an API key3. Set up your environment4. Log your first trace5. Run your first evaluationCommunityDiscordTwitterGitHubDocs CodeLangSmith SDKPythonJS/TSMoreHomepageBlogLangChain Python DocsLangChain JS/TS DocsCopyright © 2024 LangChain, Inc.\u001b[0m\u001b[32;1m\u001b[1;3mLangSmith is a platform for building production-grade LLM applications that can help with testing. It allows you to closely monitor and evaluate your application, enabling you to ship quickly and with confidence. Here are some steps to get started with LangSmith in testing:\n",
      "\n",
      "1. Install LangSmith:\n",
      "   - For Python: `pip install -U langsmith`\n",
      "   - For TypeScript: `yarn add langchain langsmith`\n",
      "\n",
      "2. Create an API key:\n",
      "   - Head to the Settings page and click on Create API Key.\n",
      "\n",
      "3. Set up your environment:\n",
      "   - Set the necessary environment variables like `LANGCHAIN_TRACING_V2`, `LANGCHAIN_API_KEY`, and `OPENAI_API_KEY`.\n",
      "\n",
      "4. Log your first trace:\n",
      "   - You can use LangSmith to log traces for testing your application.\n",
      "\n",
      "LangSmith provides tools for creating datasets, examples, and evaluators to test and evaluate your application. By defining datasets, examples, and evaluators, you can run evaluations to ensure the correctness and performance of your application.\n",
      "\n",
      "For more detailed information and guidance on using LangSmith for testing, you can refer to the LangSmith documentation and tutorials.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'how can langsmith help with testing?',\n",
       " 'output': 'LangSmith is a platform for building production-grade LLM applications that can help with testing. It allows you to closely monitor and evaluate your application, enabling you to ship quickly and with confidence. Here are some steps to get started with LangSmith in testing:\\n\\n1. Install LangSmith:\\n   - For Python: `pip install -U langsmith`\\n   - For TypeScript: `yarn add langchain langsmith`\\n\\n2. Create an API key:\\n   - Head to the Settings page and click on Create API Key.\\n\\n3. Set up your environment:\\n   - Set the necessary environment variables like `LANGCHAIN_TRACING_V2`, `LANGCHAIN_API_KEY`, and `OPENAI_API_KEY`.\\n\\n4. Log your first trace:\\n   - You can use LangSmith to log traces for testing your application.\\n\\nLangSmith provides tools for creating datasets, examples, and evaluators to test and evaluate your application. By defining datasets, examples, and evaluators, you can run evaluations to ensure the correctness and performance of your application.\\n\\nFor more detailed information and guidance on using LangSmith for testing, you can refer to the LangSmith documentation and tutorials.'}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"how can langsmith help with testing?\"})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Invoking: `tavily_search_results_json` with `{'query': 'weather in San Francisco'}`\n",
      "\n",
      "\n",
      "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.weatherapi.com/', 'content': \"{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1721781591, 'localtime': '2024-07-23 17:39'}, 'current': {'last_updated_epoch': 1721781000, 'last_updated': '2024-07-23 17:30', 'temp_c': 19.9, 'temp_f': 67.8, 'is_day': 1, 'condition': {'text': 'Sunny', 'icon': '//cdn.weatherapi.com/weather/64x64/day/113.png', 'code': 1000}, 'wind_mph': 11.2, 'wind_kph': 18.0, 'wind_degree': 259, 'wind_dir': 'W', 'pressure_mb': 1012.0, 'pressure_in': 29.88, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 59, 'cloud': 10, 'feelslike_c': 19.9, 'feelslike_f': 67.8, 'windchill_c': 19.9, 'windchill_f': 67.8, 'heatindex_c': 20.2, 'heatindex_f': 68.4, 'dewpoint_c': 11.9, 'dewpoint_f': 53.4, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 5.0, 'gust_mph': 18.1, 'gust_kph': 29.2}}\"}, {'url': 'https://www.timeanddate.com/weather/usa/san-francisco/hourly', 'content': 'Hour-by-Hour Forecast for San Francisco, California, USA. Weather Today Weather Hourly 14 Day Forecast Yesterday/Past Weather Climate (Averages) Currently: 55 °F. Passing clouds. (Weather station: San Francisco International Airport, USA). See more current weather.'}, {'url': 'https://www.wunderground.com/hourly/us/ca/san-francisco\",/date/2024-07-22', 'content': 'Current Weather for Popular Cities . San Francisco, CA warning 55 ° F Partly Cloudy; Manhattan, NY 74 ° F Sunny; Schiller Park, IL (60176) 66 ° F Partly Cloudy; Boston, MA 71 ° F Fair; Houston ...'}, {'url': 'https://forecast.weather.gov/MapClick.php?lat=37.7529881&lon=-122.4174306', 'content': 'San Francisco CA 37.75°N 122.4°W (Elev. 197 ft) Last Update: 1:31 am PDT Jul 19, 2024. Forecast Valid: 1am PDT Jul 19, 2024-6pm PDT Jul 25, 2024 . Forecast Discussion . Additional Resources. Radar & Satellite Image. Hourly Weather Forecast. ... Severe Weather ; Current Outlook Maps ; Drought ; Fire Weather ; Fronts/Precipitation Maps ...'}, {'url': 'https://tgftp.nws.noaa.gov/weather/current/KSFO.html', 'content': 'Current Weather Conditions: SAN FRANCISCO INTERNATIONAL AIRPORT , CA, United States : NWS Point Forecast for KSFO ... 2024 - 01:56 PM EDT / 2024.07.17 1756 UTC : 70.0 (21.1) 57.0 (13.9) In the 24 hours preceding Jul 17, 2024 - 03:56 AM EDT / 2024.07.17 0756 UTC : 24 Hour Summary : Time EDT (UTC) Temperature F (C)'}]\u001b[0m\u001b[32;1m\u001b[1;3mThe current weather in San Francisco is as follows:\n",
      "- Temperature: 67.8°F (19.9°C)\n",
      "- Condition: Sunny\n",
      "- Wind: 18.0 km/h from the West\n",
      "- Humidity: 59%\n",
      "- Cloud Cover: 10%\n",
      "- Visibility: 6.0 miles\n",
      "\n",
      "It seems like a pleasant day in San Francisco! You can find more detailed hourly forecasts on websites like [Time and Date](https://www.timeanddate.com/weather/usa/san-francisco/hourly) and [Weather Underground](https://www.wunderground.com/hourly/us/ca/san-francisco/date/2024-07-22).\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'whats the weather in sf?',\n",
       " 'output': 'The current weather in San Francisco is as follows:\\n- Temperature: 67.8°F (19.9°C)\\n- Condition: Sunny\\n- Wind: 18.0 km/h from the West\\n- Humidity: 59%\\n- Cloud Cover: 10%\\n- Visibility: 6.0 miles\\n\\nIt seems like a pleasant day in San Francisco! You can find more detailed hourly forecasts on websites like [Time and Date](https://www.timeanddate.com/weather/usa/san-francisco/hourly) and [Weather Underground](https://www.wunderground.com/hourly/us/ca/san-francisco/date/2024-07-22).'}"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"whats the weather in sf?\"})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Adding in memory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mHello Bob! How can I assist you today?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'hi! my name is bob',\n",
       " 'chat_history': [],\n",
       " 'output': 'Hello Bob! How can I assist you today?'}"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Here we pass in an empty list of messages for chat_history because it is the first message in the chat\n",
    "agent_executor.invoke({\"input\": \"hi! my name is bob\", \"chat_history\": []})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mYour name is Bob! How can I assist you, Bob?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'chat_history': [HumanMessage(content='hi! my name is bob'),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'input': \"what's my name?\",\n",
       " 'output': 'Your name is Bob! How can I assist you, Bob?'}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_core.messages import AIMessage, HumanMessage\n",
    "\n",
    "agent_executor.invoke(\n",
    "    {\n",
    "        \"chat_history\": [\n",
    "            HumanMessage(content=\"hi! my name is bob\"),\n",
    "            AIMessage(content=\"Hello Bob! How can I assist you today?\"),\n",
    "        ],\n",
    "        \"input\": \"what's my name?\",\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`If we want to keep track of these messages automatically, we can wrap this in a RunnableWithMessageHistory.`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_community.chat_message_histories import ChatMessageHistory\n",
    "from langchain_core.runnables.history import RunnableWithMessageHistory\n",
    "\n",
    "message_history = ChatMessageHistory()\n",
    "agent_with_chat_history = RunnableWithMessageHistory(\n",
    "    agent_executor,\n",
    "    # This is needed because in most real world scenarios, a session id is needed\n",
    "    # It isn't really used here because we are using a simple in memory ChatMessageHistory\n",
    "    lambda session_id: message_history,\n",
    "    input_messages_key=\"input\",\n",
    "    history_messages_key=\"chat_history\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Parent run 3530465e-f051-4c7c-bdfe-bde719c3d2b3 not found for run 3ceef4e1-7725-4d19-980e-8fc30ba0005e. Treating as a root run.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mHello Bob! How can I assist you today?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"hi! I'm bob\",\n",
       " 'chat_history': [],\n",
       " 'output': 'Hello Bob! How can I assist you today?'}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_with_chat_history.invoke(\n",
    "    {\"input\": \"hi! I'm bob\"},\n",
    "    # This is needed because in most real world scenarios, a session id is needed\n",
    "    # It isn't really used here because we are using a simple in memory ChatMessageHistory\n",
    "    config={\"configurable\": {\"session_id\": \"<foo>\"}},\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Parent run 4fab1aa3-1efe-427e-839d-615d736e5fee not found for run f25f0cd6-49ac-4779-8ee0-4ccbcd767df8. Treating as a root run.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mYour name is Bob! How can I help you today, Bob?\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"what's my name?\",\n",
       " 'chat_history': [HumanMessage(content=\"hi! I'm bob\"),\n",
       "  AIMessage(content='Hello Bob! How can I assist you today?')],\n",
       " 'output': 'Your name is Bob! How can I help you today, Bob?'}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_with_chat_history.invoke(\n",
    "    {\"input\": \"what's my name?\"},\n",
    "    # This is needed because in most real world scenarios, a session id is needed\n",
    "    # It isn't really used here because we are using a simple in memory ChatMessageHistory\n",
    "    config={\"configurable\": {\"session_id\": \"<foo>\"}},\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain0_1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
